﻿using dz.db.util.core;
using dz.loger.core;
using dz.u9.jky.schema.Common;
using dz.util.core;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dz.WorkerService.Service
{
    public abstract class BaseU9Service
    {
        protected string table,controller, processId, docType;
        protected Dictionary<string,string> currencys = new Dictionary<string, string>();
        protected SqlUtils sqlUtils = new SqlUtils(Config.Instance.GetConnectionString("U9"));
        protected DataTable dt;

        public BaseU9Service(string processId)
        {
            this.processId = processId;
            GetCurrenys();
        }
        
        public virtual async Task ImportData()
        {
            try
            {
                dt = await GetProcessData();

                await Process();
                await Task.CompletedTask;
            }
            catch (Exception ex)
            {
                LogUtil.Instance.Error(ex.StackTrace);
                LogUtil.Instance.Error(ex);
                throw;
            }
            
        }

        protected virtual async Task Process()
        {
            await Task.CompletedTask;
        }

        protected async virtual Task<DataTable> GetProcessData()
        {
            DataTable dataTable = new DataTable();
            await Task.Delay(0);

            return dataTable;
        }

        private void GetCurrenys()
        {
            string sql = @"select distinct b.code as org,c.code as currency
                        from Base_SetofBooks a
                        inner join Base_Organization b on a.Org = b.id
                        inner join Base_Currency c on c.id = a.FunctionalCurrency";

            DataTable dt = sqlUtils.FillSync(sql);

            foreach (DataRow item in dt.Rows)
            {
                currencys.Add(item["org"].ToString(), item["currency"].ToString());
            }

        }

        protected async Task UpdateSyncLog(U9CResult result, string extWhere = "")
        {
            if (result.IsSuccess || result.Id > 0)
            {
                await UpdateDataState(2, extWhere);
            }
            await AddSyncDetailLog(result);

        }

        /// <summary>
        /// 数据下载完成，生成U9单据后跟新数据表状态
        /// </summary>
        /// <param name="table">表名</param>
        /// <param name="type">状态 1：处理中 2：处理完成</param>
        /// <returns></returns>
        protected async Task UpdateDataState(int type, string extWhere = "")
        {
            string sql = @$"update {table} set xtype = {type} where xtype = {type} - 1 {extWhere}";

            await sqlUtils.ExecuteNonQuery(sql);
        }

        protected async Task AddSyncDetailLog(U9CResult result)
        {
            string sql = string.Empty;

            if (result.IsSuccess)
            {
                //全部成功
                sql = $@"insert into dz_hd_jkysynclog_detail(id,doctype,docno,docid,flag) 
                    values('{processId}','{docType}','{result.DocNo}',{result.Id},1)";
            }
            else
            {
                if (result.Id > 0)
                {
                    //部分成功
                    sql = $@"insert into dz_hd_jkysynclog_detail(id,doctype,docno,docid,flag) 
                    values('{processId}','{docType}','{result.DocNo}',{result.Id},2)";
                }
                else
                {
                    sql = $@"insert into dz_hd_jkysynclog_detail(id,doctype,flag,msg) 
                    values('{processId}','{docType}',-1,'{result.Message}')";
                }
            }
            await sqlUtils.ExecuteNonQuery(sql);

            sql = $"exec usp_dz_updatesynclog '{processId}','{result.Message}'";

            await sqlUtils.ExecuteNonQuery(sql);
        }
    }
}
